import 'package:dio/dio.dart';
import 'dart:convert';

Future<Response<dynamic>> getPostById({
  required int postId,
  required Dio dio,
}) async {
  Response<dynamic> response = await dio.get('/post/$postId');
  return response;
}
Future<Response<dynamic>> getAllPosts({
  required Dio dio,
}) async {
  Response<dynamic> response = await dio.get('/post');
  return response;
}
// 根据 userId 获取 Post
Future<Response<dynamic>> getPostsByUserId({
  required int userId,
  required Dio dio,
}) async {
  Response<dynamic> response = await dio.get('/post/userId/$userId');
  return response;
}

// 根据 title 获取 Post
Future<Response<dynamic>> getPostsByTitle({
  required String title,
  required Dio dio,
}) async {
  Response<dynamic> response = await dio.get('/post/title/$title');
  return response;
}

// 添加新的 Post
Future<Response<dynamic>> addNewPost({
  required int userId,
  required Map<String, dynamic> postDTO,
  required Dio dio,
  String? imagePath, // 允许传递空值
}) async {
  final Map<String, dynamic> formDataMap = {
    'postDTO': jsonEncode(postDTO),
  };

  if (imagePath != null && imagePath.isNotEmpty) {
    formDataMap['imageFile'] = await MultipartFile.fromFile(imagePath, filename: imagePath.split('/').last);
  }

  FormData formData = FormData.fromMap(formDataMap);

  Options options = Options(
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  );

  try {
    Response<dynamic> response = await dio.post(
      '/post/$userId',
      data: formData,
      options: options,
    );
    return response;
  } catch (e) {
    print('Error: $e');
    throw e;
  }
}

// 更新 Post
Future<Response<dynamic>> updatePostById({
  required int id,
  String? title,
  String? content,
  String? publicationDate,
  int? likesCount,
  int? commentsCount,
  int? sharesCount,
  int? favoritesCount,
  required Dio dio,
}) async {
  Map<String, dynamic> queryParams = {};
  if (title != null) queryParams['title'] = title;
  if (content != null) queryParams['content'] = content;
  if (publicationDate != null) queryParams['publicationDate'] = publicationDate;
  if (likesCount != null) queryParams['likesCount'] = likesCount.toString();
  if (commentsCount != null) queryParams['commentsCount'] = commentsCount.toString();
  if (sharesCount != null) queryParams['sharesCount'] = sharesCount.toString();
  if (favoritesCount != null) queryParams['favoritesCount'] = favoritesCount.toString();

  Response<dynamic> response = await dio.put(
    '/post/$id',
    queryParameters: queryParams,
  );
  return response;
}

// 删除 Post
Future<Response<dynamic>> deletePostById({
  required int id,
  required Dio dio,
}) async {
  Response<dynamic> response = await dio.delete('/post/$id');
  return response;
}

